package com.example.aidlclient

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.IBinder
import android.os.Looper
import android.os.RemoteException
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import com.example.aidlclient.aidl.Book
import com.example.aidlclient.aidl.IBookManager
import com.example.aidlclient.aidl.IOnCountListener

class MainActivity : AppCompatActivity() {

    lateinit var bookManager: IBookManager

    private val mListener = object : IOnCountListener.Stub() {
        override fun onCountChanged(count: Int) {
            LogUtil.d("onCountChanged -> " + Thread.currentThread())
            Toast.makeText(baseContext, "count:$count", Toast.LENGTH_LONG).show()
        }
    }

    private var conn: ServiceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName, service: IBinder) {
            LogUtil.e("onServiceConnected: " + Thread.currentThread())
            bookManager = IBookManager.Stub.asInterface(service)
            bookManager.registerListener(mListener)
        }

        override fun onServiceDisconnected(name: ComponentName) {

        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val intent = Intent(this, BookService::class.java)
        bindService(intent, conn, Context.BIND_AUTO_CREATE)

        var counter = 3
        findViewById<Button>(R.id.btn_add).setOnClickListener {
            val newBook = Book(counter, "Android 进阶" + counter)
            counter++
            try {
                bookManager.addBook(newBook)
            } catch (e: RemoteException) {
                e.printStackTrace()
            }
        }

        findViewById<Button>(R.id.btn_test).setOnClickListener {
            bookManager.printBook()
        }

        findViewById<Button>(R.id.btn_show).setOnClickListener {
            try {
                val list = bookManager.bookList
                findViewById<TextView>(R.id.textView).text = list.toString()
            } catch (e: RemoteException) {
                e.printStackTrace()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        bookManager.unregisterListener(mListener)
    }
}
